package com.teacher.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.pojo.dto.wx.WxLoginDto;
import com.teacher.pojo.dto.wx.WxValidDto;
import com.teacher.service.IPerStudentService;
import com.teacher.service.IPerTeacherService;
import com.teacher.service.IWechatUserService;
import com.teacher.pojo.entity.WechatUser;
import com.teacher.mapper.WechatUserMapper;
import com.teacher.security.entity.security.RedisUserInfo;
import com.teacher.security.service.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 微信用户接口表 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2020-12-16
 */
@Service
@Slf4j
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements IWechatUserService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private IPerStudentService iPerStudentService;

    @Autowired
    private IPerTeacherService iPerTeacherService;


    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private IRedisService iRedisService;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Override
    public CommonResult login(WxLoginDto dto) {

        RedisUserInfo redisUserInfo = new RedisUserInfo();

        String url = "https://api.weixin.qq.com/sns/jscode2session?";

        ConcurrentHashMap<String, Object> concurrentHashMap = new ConcurrentHashMap<>();

        redisUserInfo.setPermissionValue(new ArrayList<>());
        redisUserInfo.setAllMenu(new ArrayList<>());

        String appid = "wx2264bec6c2fa8fe9";

        String secret = "3704ffabfd4fe0481c2083dbc556cc7a";

        RestTemplate restTemplate = new RestTemplate();

        String json = restTemplate.getForObject(url + "appid=" + appid + "&secret=" + secret + "&js_code=" + dto.getCode()
                + "&grant_type=authorization_code", String.class);

        String openid = JSONUtil.parseObj(json).getStr("openid");

        // 判定是否登录过小程序

        if (openid == null) {
            return CommonResult.failed("请求错误 ");
        }
        WechatUser wechatUser = baseMapper.selectOne(new QueryWrapper<WechatUser>().lambda()
                .eq(WechatUser::getOpenId, openid));
        // 完全未登录过
        if (wechatUser == null) {
            wechatUser = new WechatUser();
            wechatUser.setOpenId(openid);
            concurrentHashMap.put("code", -1);
            concurrentHashMap.put("sname", jwtTokenUtil.generateToken(openid));
            iRedisService.set(openid, JSONUtil.toJsonStr(redisUserInfo));
            iRedisService.expire(openid, expiration);
            return CommonResult.success(concurrentHashMap);
        } else {
            // 查询用户 返回 token
            wechatUser.setLastLogin(new Date());
            // 记录最后一次登录时间
            baseMapper.updateById(wechatUser);
            concurrentHashMap.put("sname", jwtTokenUtil.generateToken(wechatUser.getId() + ""));
            concurrentHashMap.put("code", 1);
            iRedisService.set(wechatUser.getId() + "", JSONUtil.toJsonStr(redisUserInfo));
            iRedisService.expire(wechatUser.getId() + "", expiration);
            return CommonResult.success(concurrentHashMap);
        }
    }

    /**
     * 校验用户
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult valid(WxValidDto dto) {



        return CommonResult.failed("校验失败");
    }
}
